import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_base/src/core/bloc_page/bloc_base_page.dart';

///App中的Base界面
///* 该界面主要为个别没有appbar的界面服务，具有更少的Widget嵌套
abstract class BasePage<B extends PageBloc> extends StatefulWidget {
  BasePage({Key key}) : super(key: key);

  @override
  State<BasePage> createState() {
    onCreateState();
    return _BasePageState<B>();
  }

  B getPageBloc();

  Key getProviderKey() {
    return null;
  }

  List<BlocProvider> getExtraBlocProviderList() {
    return null;
  }

  void onCreateState() {}

  void onInitState(B pageBloc);

  void onBuild(B pageBloc) {}

  void onDispose(B pageBloc, {List<BlocProvider> blocProviderList}) {}
}

class _BasePageState<B extends PageBloc> extends State<BasePage<B>> {
  B pageBloc;
  List<BlocProvider> blocProviderList;

  @override
  void initState() {
    super.initState();
    pageBloc = widget.getPageBloc();
    blocProviderList =
        (widget.getExtraBlocProviderList() ?? List<BlocProvider>())
          ..add(BlocProvider<B>(
            builder: (context) => pageBloc,
          ));
    widget?.onInitState(pageBloc);
  }

  @override
  Widget build(BuildContext context) {
    pageBloc.context = context;
    widget.onBuild(pageBloc);
    return MultiBlocProvider(
      key: widget.getProviderKey(),
      providers: blocProviderList,
      child: getChild(),
    );
  }

  @override
  void dispose() {
    widget.onDispose(pageBloc, blocProviderList: blocProviderList);
    super.dispose();
  }

  Widget getChild() {
    return BlocBuilder(
      bloc: pageBloc,
      builder: (BuildContext context, PageState state) {
        if (state is PageBuildState) {
          return state.pageBuilder(context);
        }
        return Container();
      },
    );
  }
}
